<template>
    <div class="modal-overlay" @click="closeModal" >
        <div class="modal-content" @click.stop>
                <div class="rounded-rectangle">
                    <div class="leftrounded" >
                        <el-carousel :interval="0" :autoplay="false"  arrow="always" height="100%" >
                            <el-carousel-item v-for= "(image,index) in imageUrls" :key="index">
                                <a :href="image" target="_blank">
                                    <img :src="image" alt="image" class="carousel-image"/>
                                </a>
                            </el-carousel-item>
                        </el-carousel>
                    </div>
                    <div class="rightrounded">
                        <el-scrollbar class="right-content-scrollbar">
                            <!-- 第一块，占比10% -->
                            <div class="demo-type-section"  style="display: flex; align-items: center; justify-content: space-between; ">
                                <el-avatar
                                    :class="'avatar'"  :src="ProfilePhoto"
                                    :fit="'cover'"  :shape="'circle'"  :size="50"
                                    @click="avaClick"
                                />
                                <p style="font-size: 20px; margin-left: 15px;">{{UName}}</p>
                                <span style="flex-grow: 1;"></span>
                                <el-button v-if="userID !== AuthorID " type="warning" color="#FFD466" class="large-button"
                                               :class="{ 'followed-button': isFollow }"  @click="handleFollowClick">
                                        {{ buttonText }}
                                </el-button>
                            </div>
                            <!-- 第二块，占比45% -->
                            <div class="title-section" style="min-height: 0; display: flex; flex-direction: column;">
                                <div class="text-box">
                                    <p class="title">{{title}}</p>
                                    <p class="content">{{content}}</p>
                                    <div style="display: flex; align-items: center; justify-content: space-between;">
                                        <el-icon color="#FFD466" :size="25" font-weight: bold><Location /></el-icon>
                                        <p class="vocation">{{vocation}}</p>
                                        <span style="flex-grow: 1;"></span>
                                        <p class="vocation">{{time}}</p>
                                    </div>
                                </div>
                            </div>
                            <!-- 第三块，占比37% -->
                            <div class="comments" style="height: 37%;">
                                <hr style="width: 98%; margin-bottom:5px; color: grey ">
                                <CommentList  :comments="comments" :isAdopt =false :textcount="textcounter"  @updateTextCounter="updateTextCounter" @toggle-replies="toggleReplies" />
                            </div>
                        </el-scrollbar>
                        <!-- 第四块，占比10% -->
                        <div class="button-container-section" style="display: flex; align-items: center; justify-content: space-between; height: 8%; position: relative; bottom: 0; background-color: white;">
                            <div v-if="!isInputVisible" class="comment-apply">
                                <el-button round
                                           class="custom-button"
                                           :hover="{ backgroundColor: '#f0f0f0' }"
                                            @click="firstcomment">
                                    <el-avatar
                                        :class="'avatar'"
                                        :src="UserAvatar"
                                        :fit="'cover'"
                                        :shape="'circle'"
                                        :size="40"
                                    />
                                    <p style="font-family: Arial, sans-serif; font-size: 20px; font-weight: bold;  margin-left: 20px; margin-right: 160px; color: rgba(0, 0, 0, 0.3);">说点什么...</p>
                                </el-button>
                            </div>
                            <div v-if="isInputVisible" class="input-box-wrapper" style="flex: 1; z-index: 1;">
                                <div class="input-box-container">
                                    <el-scrollbar class="input-scrollbar">
                                        <el-input
                                            type="textarea"
                                            :rows="inputRows"
                                            v-model="inputText"
                                            :placeholder= "PlaceholderText"
                                            @input= "adjustInputRows"
                                        />
                                    </el-scrollbar>
                                </div>
                                <div class="button-group">
                                    <el-button type="warning" color="#FFD466" class="large-button1 " @click="sendMessage">发送</el-button>
                                    <el-button type="info" class="large-button1 "  @click="toggleToInput">取消</el-button>
                                </div>
                            </div>
                            <span v-if="!isInputVisible" style="flex-grow: 0;margin-left: 20px;"></span>
                            <div v-if="!isInputVisible">
                                <label class="container">
                                    <input type="checkbox" v-model = "isChecked" @click="passageLike">
                                    <div class="checkmark">
                                        <svg viewBox="0 0 256 256">
                                            <rect fill="none" height="256" width="256"></rect>
                                            <path class="like" d="M224.6,51.9a59.5,59.5,0,0,0-43-19.9,60.5,60.5,0,0,0-44,17.6L128,59.1l-7.5-7.4C97.2,28.3,59.2,26.3,35.9,47.4a59.9,59.9,0,0,0-2.3,87l83.1,83.1a15.9,15.9,0,0,0,22.6,0l81-81C243.7,113.2,245.6,75.2,224.6,51.9Z"
                                                  stroke-width="18px" stroke="#000000" fill="none"></path></svg>
                                    </div>
                                </label>
                            </div>

                            <p v-if="!isInputVisible" style="font-family: Arial, sans-serif; font-size: 22px;  margin : auto ;"> {{ counter }}</p>
                            <el-icon v-if="!isInputVisible" :size="25" @click="firstcomment">
                                <ChatDotRound />
                            </el-icon>
                            <p v-if="!isInputVisible" style="font-family: Arial, sans-serif; font-size: 22px;  margin : auto ; "> {{ textcounter }}</p>
                        </div>
                    </div>
                </div>
        </div>
    </div>
</template>

<script setup>
import {onMounted, ref, defineEmits} from 'vue';
import CommentList from '@/components/CommentList.vue';

import axios from 'axios';
import router from "@/router";
import {ElMessage} from "element-plus";

const token = ref('');
const imageUrls = ref([]);//1
//右边第一块
const UName = ref('用户名');   //2
const AuthorID = ref('1');    //3
const isFollowed = ref(0); //4 是否关注
const isFollow =ref(false);   //控制关注按钮颜色
// 定义按钮文本的响应式数据
const buttonText = ref('关注');
// 定义点击按钮的处理函数，关注和取消关注的接口调用

// 设置axios的默认请求头，用于后续请求携带token
axios.defaults.headers.common['Authorization'] = ` ${token.value}`;
const avaClick = () => {
    const data = { id:AuthorID.value };
    sessionStorage.setItem('userData', JSON.stringify(data));
    router.push({
        path:'/UserPage',
        query: {
            id: AuthorID.value,
        }
    })
    location.reload();
}
const handleFollowClick = async () => {
    const action = isFollowed.value == 1 ? 'delete' : 'add';
    try {
        const response = await axios.post(`http://localhost:8080/focus/${action}`, {
            FocusID: AuthorID.value });
        if (response.status === 200) {
            if(action == 'add'){
                isFollowed.value = 1;
                isFollow.value = true;
            }
            else{
                isFollowed.value = 2;
                isFollow.value = false;
            }
            buttonText.value = isFollowed.value === 1 ? '已关注' : '关注';
        } else {
            console.error('操作失败:', response.data.message);
            alert('操作失败');
        }
    } catch (error) {
        console.error('请求失败:', error);
        alert('请求失败，请再次尝试');
    }
};
//右边第二块
const title = ref('');  //5
const content = ref('');  //6
const ProfilePhoto = ref('') //头像
const vocation = ref('') ; //7
const time = ref('');  // 8
//右边第三块
// 评论数据
const comments = ref([]);
const ReplyUserID = ref(0);   //被回复评论的ID
const CommentReplylD = ref(0) //被回复评论的用户ID
const ParentID = ref(0);   //顶级评论ID
const replyType = ref(0);   //回复那条评论的类型
const PlaceholderText = ref('');  //回复内容
//评论的回复
const toggleReplies = (commentIndex,parentID,commentID,replyUserID,username,type) => {
    ParentID.value = parentID;
    ReplyUserID.value = replyUserID;
    CommentReplylD.value = commentID;
    replyType.value =  type;
    PlaceholderText.value = '回复'+username;
    toggleToInput();
};
const updateTextCounter = (newValue) => {
    textcounter.value = newValue;
};
//右边第四块
const textcounter = ref(0);  //7
const PassageID = ref(0);
// 按钮点击事件处理函数
const isInputVisible = ref(false);
const inputText = ref('');  //评论
const inputRows = ref(1); // 初始行数
const userData0 = JSON.parse(sessionStorage.getItem('token'));
const userID = userData0.userID;

//第一条评论
const firstcomment = () =>{
    replyType.value = 1 ; //返回第一条评论类型
    ReplyUserID.value = 0; // 清零
    ParentID.value = 0;
    CommentReplylD.value = 0;
    PlaceholderText.value = '请输入内容';
    toggleToInput();
}
const toggleToInput = () => {
    isInputVisible.value =!isInputVisible.value;
    if (!isInputVisible.value) {
        inputText.value = '';
        inputRows.value = 1;
    }
};

// 发送消息的方法
const sendMessage = async () => {
    if (inputText.value.trim() === '' ) {
        // 进行简单验证，如果输入内容为空，则提示用户
        ElMessage({
            message: '请输入内容',
            type: 'warning',
            style: 'font-size:25px;font-weight:bold;',
            offset: 55,
            grouping:true
        })
        return;
    }
    const dataToSend = {
        PassageID: PassageID.value,    //文章ID
        ReplyUserID: ReplyUserID.value,  //被回复的评论的用户ID
        CommentContent: inputText.value,    //评论内容
        CommentType: replyType.value,  //评论类型
        ParentID :  ParentID.value,  //父评论ID
        CommentReplyID : CommentReplylD.value,//评论发布者的ID
    };
    try {
        const response = await axios.post('http://localhost:8080/comment/upload', dataToSend);
        console.log('消息发送成功，后端返回：', response.data);
        ElMessage({
            message: '评论成功',
            type: 'success',
            style: 'font-size:25px;font-weight:bold;',
            offset: 55,
            grouping:true
        })
        inputText.value = '';
        inputRows.value = 1;
        // 调用toggleToInput函数切换回输入状态，这里简单实现为清空输入框内容，可根据实际功能调整
        toggleToInput();
        console.log(textcounter);
        textcounter.value++;
        console.log(textcounter);
        replyType.value = 0 ; //返回第一条评论类型
        ReplyUserID.value = 0; // 清零
    } catch (error) {
        console.error('消息发送失败：', error);
        alert('消息发送失败，请再次尝试');
    }
    const response1 = await axios.get('http://localhost:8080/comment/list/' + PassageID.value, {});
    if(response1.status === 200) {
        comments.value = response1.data.data;
    }
};
const adjustInputRows = () => {
    const lines = inputText.value.split('\n').length;
    inputRows.value = Math.max(lines, 1);
};
// 爱心 用于绑定复选框的选中状态
const isChecked = ref(false);
// 用于记录点击次数的计数器
const counter = ref(0);    //8
// 监听复选框的变化，当选中时增加计数器的值

const passageLike = async() => {
  if (!isChecked.value) {
    try {
        const response = await axios.post('http://localhost:8080/likes/passage/add', {
          PassageID: PassageID.value
        });
        if (response.status === 200) {
          counter.value++;
          sessionStorage.setItem('likeNum',counter.value)
          emit('likeEvent', isChecked.value);
          ElMessage({
            message: '点赞成功',
            type: 'success',
            style: 'font-size:25px;font-weight:bold;',
            offset: 55,
            grouping:true
          })
        }
    } catch (error) {
      ElMessage({
        message: '点赞失败，请再次尝试',
        type: 'error',
        style: 'font-size:25px;font-weight:bold;',
        offset: 55,
        grouping:true
      })
      isChecked.value = false; // 点赞失败，将isChecked恢复为false
      emit('likeEvent', isChecked.value);
      return; // 直接返回，不再执行后续取消点赞相关逻辑
    }
  } else {
     // 只有点赞成功过，才执行取消点赞操作
      try {
        const response = await axios.post('http://localhost:8080/likes/passage/undo', {
          PassageID: PassageID.value
        });
        if (response.status === 200) {
          counter.value--;
          sessionStorage.setItem('likeNum',counter.value)
          emit('likeEvent', isChecked.value);
          ElMessage({
            message: '取消点赞成功',
            type: 'success',
            style: 'font-size:25px;font-weight:bold;',
            offset: 55,
            grouping:true
          })
        }
      } catch (error) {
        isChecked.value = true;
        ElMessage({
          message: '取消点赞失败，请再次尝试',
          type: 'error',
          style: 'font-size:25px;font-weight:bold;',
          offset: 55,
          grouping:true
        })
        emit('likeEvent', isChecked.value);
        return;
      }
  }
}
const UserAvatar = ref('');
onMounted(async () => {
    setTimeout(async() => {
      console.log("passageDialog渲染")
      const userData = JSON.parse(sessionStorage.getItem('token'));
      token.value = userData.token;
      const response2 = await axios.get('http://localhost:8080/users/'+ userData.userID,{})
        if(response2.status==200){
            UserAvatar.value = response2.data.ProfilePhoto;
        }
        const userData1 = JSON.parse(sessionStorage.getItem('PassageID'));
      PassageID.value = userData1.PassageID;
      axios.defaults.headers.common['Authorization'] = `${userData.token}`;
      const response = await axios.get('http://localhost:8080/passage/content/'+ PassageID.value ,{});// 获取用户名
      console.log(response.data);
      AuthorID.value = response.data.AuthorID;   //作者ID 1
      UName.value = response.data.UName;         //作者名称 2
      ProfilePhoto.value = response.data.ProfilePhoto;   //作者头像
      isFollowed.value = response.data.ifSubscribe;  //是否关注 3
      buttonText.value = isFollowed.value == 1  ? '已关注' : '关注';
      isFollow.value = isFollowed.value == 1  ? true : false;
      title.value = response.data.PassageTitle;   //标题 4
      content.value = response.data.PassageContent;  //内容 5
      vocation.value = response.data.PassageArea;  //地区 6
      time.value = response.data.PassageTime; //发布时间 7
      imageUrls.value = response.data.PassagePicList;  //需要改 8
      textcounter.value = response.data.CommentNum;  //评论数 9
      setTimeout(() => {
        counter.value = sessionStorage.getItem('likeNum') //点赞数  10
        console.log("子组件点赞数：",counter.value)
      },50)

      isChecked.value = response.data.ifLiked//是否点赞  11
      console.log("isChecked",isChecked.value)
      const response1 = await axios.get('http://localhost:8080/comment/list/' + userData1.PassageID, {});
      if(response1.status === 200) {
        comments.value = response1.data.data;
      }
    },1)
    console.log(comments);
})
//定义关闭模态框的方法并向父组件发送关闭事件
const closeModal = () => {
    emit('close');
    inputText.value = '';
    isInputVisible.value = true;
    /*props.visible.value = false;*/
    toggleToInput();
};
// 定义 emits
const emit = defineEmits(['close','likeEvent']);
</script>

<style scoped>
.modal-overlay {   /*弹窗主页面*/
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    //background: rgba(0, 0, 0, 0); /* 背景虚化 */
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1;
}

.modal-content {   /*弹窗设计*/
    background: white;  /*白色背景*/
    padding: 20px;     /* 上下左右间距*/
    border-radius: 20px ;  /*角圆弧*/
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);  /*四周阴影*/
    width: 70%; /* 设置宽度为页面的70% */
    height: 80%; /* 设置高度为页面的80% */
    overflow: auto;   /*自动适应页面大小*/
}

.rounded-rectangle {  /*再里面的长方形*/
    border-radius: 20px; /* 圆弧长方形 */
    background: white;
    text-align: center;
    width: 100%; /* 设置宽度为页面的100% */
    height: 100%; /* 设置高度为页面的100% */
    margin: auto; /* 自动居中 */
    display: flex; /* 使用 Flexbox 布局 */
    /*justify-content: space-between; !* 左右两部分之间留有空间 *!*/
    position: relative; /* 相对定位，用于绝对定位关闭按钮 */
}

.leftrounded, .rightrounded {
    flex: 1; /* 左右两部分各占一半宽度 */
    width: 98%; /* 设置宽度为页面的100% */
    height: 98%; /* 设置高度为页面的100% */
}
.carousel-image {
    width: 100%;
    height: 100%;
    object-fit: contain;
}
.el-carousel {
    width: 100%;
    height: 100%;
}
.el-carousel__item h3 {
    color: #475669;
    opacity: 0.75;
    line-height: 500px;
    margin: 0;
    text-align: center;
}

.rightrounded {
    background: white; /* 右边部分的背景颜色 */
    border-radius: 20px; /* 圆弧长方形 */
    display: flex;
    flex-direction: column; /*竖直排布*/
    justify-content: center; /*居中*/
    margin-left: 20px;
    padding-bottom: 30px;
}
.right-content-scrollbar {
    height: 100%; /* 设置滚动条容器高度占满父容器 */
    overflow: auto; /* 当内容超出时显示滚动条 */
    margin-right : -10px;
}
.el-avatar{
    cursor: pointer;
}
.followed-button {
  background-color: #A6A6A6;
  border-color: #A6A6A6;
}
.followed-button:hover{
  background-color: #BCBCBC;
  border-color: #BCBCBC;
  color:white;
}
.large-button {
  width:75px;
  height:35px;
  border-radius: 11px;
  font-size: 16px;
  margin-right: 20px;
  color:white;
  font-weight: bold;
}
.large-button:hover{
  color:white;
}
/*右边第二块文字格式*/
.title-section {
    display: flex;
    justify-content: flex-start;
    text-align: left;
    margin-top: 15px;
}
.text-box {
    display: flex;
    flex-direction: column;
    position: relative;
}
.title {
    font-size: 25px;
    font-weight: bold;
    text-align: left;
    margin-bottom: 2px;
    margin-top: -8px;
}
.content {
    font-size: 17px;
    text-align: left;
    margin-bottom: 5px;
    margin-left: 6px;
    margin-right: 14px;
}
.vocation{
    font-size: 15px;
    margin-right: 20px;
}
/*第三个评论区*/
.comments{
    margin-bottom: 10px;
}

/*第四块评论框*/
.button-container-section{
    margin-top: 10px;
    margin-bottom: -10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: relative;
}
.custom-button {
    width: 330px; /* 调整按钮宽度 */
    height: 50px; /* 调整按钮高度 */
    background-color: #ebebeb; /* 灰色背景 */
    border-color: #ebebeb; /* 边框颜色与背景一致 */
    color: #333; /* 文字颜色 */
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: -10px;
}
.custom-button:hover {
    background-color: #D3D3D3; /* 一种浅灰色的十六进制表示 */
    border-color: #D3D3D3;  /* 边框颜色与背景一致 */
}
.button-group {
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
}
.large-button1 {
  font-size: 15px; /* 放大按钮 */
  width:60px;
  border-radius: 10px;
  color:white;
  height:35px;
  font-weight:bold;
}
.large-button1:hover{
  color:white;
}
/*like动效*/
/* From Uiverse.io by KSAplay */
.container input {
    position: absolute;
    opacity: 0;
    cursor: pointer;
    height: 0;
    width: 0;
}

.container {
    display: block;
    position: relative;
    cursor: pointer;
    user-select: none;
    transition: 100ms;
    margin-left : 10px;
}

.checkmark {
    top: 0;
    left: 0;
    height: 25px;
    width: 25px;
    transition: 100ms;
    animation: dislike_effect 500ms ease;
    margin-left: 10px;
}

.container input:checked ~ .checkmark path {
    fill: #FFD466;
    stroke-width: 0;
}

.container input:checked ~ .checkmark {
    animation: like_effect 400ms ease;
}

.container:hover {
    transform: scale(1.2);
}
.container:hover .like{
    stroke:#FFD466;
}

@keyframes like_effect {
    0% {
        transform: scale(0);
    }
    50% {
        transform: scale(1.2);
    }
    100% {
        transform: scale(1);
    }
}

@keyframes dislike_effect {
    0% {
        transform: scale(0);
    }
    50% {
        transform: scale(1.2);
    }
    100% {
        transform: scale(1);
    }
}

.full-size-scrollbar {
    height: 100%; /* 设置高度为100% */
}
.el-icon{
    cursor: pointer;
}

</style>
